package JavaEE_notes.common_API;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * 对属性文件 properties的操作类
 * @author TaiZai
 * @data 2024/9/24 10:42
 */
public class api_Properties {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        // 加载数据到properties中
        properties.load(new FileReader("src/main/resources/wlwlwl.properties"));
        // 根据键读值
        System.out.println(properties.getProperty("小明"));
        // 遍历全部的键和值
        properties.forEach((key, value) -> System.out.println(key + " = " + value));

        // 写入数据到属性文件中
        // 创建一个Properties集合，先存储一些键值对数据
        Properties properties1 = new Properties();
        properties1.setProperty("小红", "2020202");
        properties1.setProperty("李华","121212");
        // 再将 properties1中的数据写入到属性文件中 comments是注释
        properties1.store(new FileWriter("src/main/resources/wlwlwl_new.properties"), "Update properties");

        // 读取属性文件并验证是否修改成功
        Properties properties2 = new Properties();
        properties2.load(new FileReader("src/main/resources/wlwlwl_new.properties"));
        System.out.println(properties2.getProperty("小红")); // 2020202
        System.out.println(properties2.getProperty("李华")); // 121212

    }
}
